#include "reactor_msgserver.h"

#include <QDebug>
#include "databasemagr.h"

Reactor_MsgServer::Reactor_MsgServer(int port, EventLoop *loop, ThreadPool *pool, QObject *parent): QObject(parent)
{
    m_server = new TcpServer(port, loop, pool); ///1. 创建TcpServer
    ///2. 绑定处理新连接请求的回调函数
    m_server->createNewConnectCallback(std::bind(&Reactor_MsgServer::newTcpConnection, this, std::placeholders::_1));
}
bool Reactor_MsgServer::startListen(void)
{
    return m_server->listen(); ///3. 调用TcpServer::listen()开始监听客户端的链接请求
}

///4. 实现新连接请求的回调函数，获取分配的Socket*
void Reactor_MsgServer::newTcpConnection(TcpSocket *socket)
{
    static int uCount = 0;
    qDebug() << "Reactor_MsgServer::newTcpConnection: " << ++uCount;
    ///5. 创建MsgServer,将socket给MsgSocket使用
    Reactor_MsgSocket *client = new Reactor_MsgSocket(socket);
    connect(client, SIGNAL(signalConnected()),
            this, SLOT(SltConnected()));
    connect(client, SIGNAL(signalDisConnected()),
            this, SLOT(SltDisConnected()));
}

/**
 * @brief Reactor_MsgServer::SltConnected
 * 通过验证后，才可以加入容器进行管理
 */
void Reactor_MsgServer::SltConnected()
{
    Reactor_MsgSocket *client = (Reactor_MsgSocket *)this->sender();
    if (NULL == client) return;

    connect(client, SIGNAL(signalMsgToClient(quint8,int,QJsonValue)),
            this, SLOT(SltMsgToClient(quint8,int,QJsonValue)));
    connect(client, SIGNAL(signalDownloadFile(QJsonValue)),
            this, SIGNAL(signalDownloadFile(QJsonValue)));

    emit signalUserStatus(QString("用户 [%1] 上线").arg(DataBaseMagr::Instance()->GetUserName(client->GetUserId())));
    m_clients.push_back(client);
}

Reactor_MsgServer::~Reactor_MsgServer()
{
    qDebug() << "tcp server close";
    foreach(Reactor_MsgSocket *client, m_clients)
    {
        client->SltDisconnected();
        m_clients.removeOne(client);
        delete client;
    }
}

/**
 * @brief Reactor_MsgServer::SltDisConnected
 * 有客户端下线
 */
void Reactor_MsgServer::SltDisConnected()
{
    Reactor_MsgSocket *client = (Reactor_MsgSocket *)this->sender();
    if (NULL == client) return;

    for (int i = 0; i < m_clients.size(); i++) {
        if (client == m_clients.at(i))
        {
            m_clients.remove(i);
            emit signalUserStatus(QString("用户 [%1] 下线").arg(DataBaseMagr::Instance()->GetUserName(client->GetUserId())));
            return;
        }
    }

    disconnect(client, SIGNAL(signalConnected()),
               this, SLOT(SltConnected()));
    disconnect(client, SIGNAL(signalDisConnected()),
               this, SLOT(SltDisConnected()));
    disconnect(client, SIGNAL(signalMsgToClient(quint8,int,QJsonValue)),
               this, SLOT(SltMsgToClient(quint8,int,QJsonValue)));
    disconnect(client, SIGNAL(signalDownloadFile(QJsonValue)),
               this, SIGNAL(signalDownloadFile(QJsonValue)));
}

/**
 * @brief Reactor_MsgServer::SltMsgToClient
 * 消息转发控制
 * @param userId
 * @param msg
 */
void Reactor_MsgServer::SltMsgToClient(const quint8 &type, const int &id, const QJsonValue &json)
{
    // 查找要发送过去的id
    for (int i = 0; i < m_clients.size(); i++) {
        if (id == m_clients.at(i)->GetUserId())
        {
            m_clients.at(i)->SltSendMessage(type, json);
            return;
        }
    }
}

/**
 * @brief Reactor_MsgServer::SltTransFileToClient
 * @param userId
 * @param fileName
 */
void Reactor_MsgServer::SltTransFileToClient(const int &userId, const QJsonValue &json)
{
    // 查找要发送过去的id
    for (int i = 0; i < m_clients.size(); i++) {
        if (userId == m_clients.at(i)->GetUserId())
        {
//            m_clients.at(i)->SltSendMessage(SendFile, json);
            return;
        }
    }
}
